<template>
  <el-dialog
      top="10vh"
      width="600px"
      title="添加/编辑"
      :visible.sync="dialogValue"
      :close-on-click-modal="false"
      append-to-body
  >
    <SubmitForm
        :rule-form="ruleForm"
        :rules="rules"
        :form-list="formList"
        @change="handleFormChange"
        @save="onSave"
        @close="dialogValue = false"
    />
  </el-dialog>
</template>

<script>
import {http} from '@/api'

export default {
  name: 'FormAdd',
  data() {
    return {
      apiKey: 'post',
      dialogValue: false,
      ruleForm: {},
      defaultForm: {
        title: '',
        user_id: '',
        content: '',
        images: '',
        status: 1
      },
      rules: {
        // title: [{required: true, message: '标题不能为空'}],
        content: [{required: true, message: '内容不能为空'}],
        user_id: [{required: true, message: '请选择用户'}],
      },
      formList: [
        // {
        //   label: '标题',
        //   prop: 'title',
        //   name: 'input',
        //   colSpan: 24,
        //   placeholder: '请输入标题'
        // },
        {
          label: '用户ID',
          prop: 'user_id',
          name: 'select',
          colSpan: 24,
          placeholder: '请选择用户',
          options: []
        },
        {
          label: '内容',
          prop: 'content',
          name: 'input',
          type: 'textarea',
          colSpan: 24,
          placeholder: '请输入内容',
          rows: 6
        },
        {
          label: '图片',
          prop: 'images',
          name: 'file',
          colSpan: 24,
          multiple: true
        },
        {
          label: '状态',
          prop: 'status',
          name: 'select',
          colSpan: 24,
          options: [
            { label: '正常', value: 1 },
            { label: '待审核', value: -1 },
            { label: '屏蔽', value: 0 }
          ]
        },
      ]
    }
  },
  methods: {
    handleFormChange({key, val}) {

    },
    async getUserList() {
      try {
        const res = await http.user.list()
        const userOptions = res.data.map(item => ({
          label: item.name || item.nickname,
          value: item.id
        }))
        this.formList.find(item => item.prop === 'user_id').options = userOptions
      } catch (error) {
        console.error('获取用户列表失败:', error)
      }
    },
    open(row) {
      this.dialogValue = true
      this.getUserList()
      if (row) {
        http[this.apiKey].read(row.id).then(res => {
          const data = res.data
          this.ruleForm = {
            ...data,
          }
        })
      } else {
        this.ruleForm = {
          ...this.defaultForm
        }
      }
    },
    onSave() {
      const data = {
        ...this.ruleForm,
      }
      http[this.apiKey][this.ruleForm.id ? 'update' : 'create'](this.ruleForm.id, data).then(res => {
        this.$message.success('操作成功')
        this.dialogValue = false
        this.$emit('get-page')
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
